import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login'
import HomePage from '../views/homePage'
import roomMsg from "../views/roomMsg";
import Registration from "../views/registration";
import drinks from "../views/drinks";
import bill from "../views/bill";
import order from "../views/order";
import shop from "../views/shop";
import defaultPage from "../views/defaultPage"
import vipMsg from "../views/vipMsg";
import axios from "axios";
import * as path from "path";
import error from "../views/error";
Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    name:'login',
    component:Login
  },
  {
    path: '/error',
    name:'error',
    component: error
  },
  {
    path:'/homePage',
    component:HomePage,
    redirect:'/homePage/defaultPage',
    children:[
      {
        path:'/homePage/defaultPage',
        component: defaultPage
      },
      {
        path:'/homePage/roomMsg',
        name:'roomMsg',
        component:roomMsg
      },
      {
        path:'/homePage/registration',
        name: 'registration',
        component: Registration
      },
      {
        path:'/homePage/drinks',
        name: 'drinks',
        component:drinks
      },
      {
        path:'/homePage/vipMsg',
        name: 'vipMsg',
        component:vipMsg
      },
      {
        path: '/homePage/bill',
        name: 'bill',
        component:bill
      }
    ]
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{
  if (to.path.startsWith('/')){
    window.localStorage.removeItem('admin')
    next()
  }else {
    let admin = JSON.parse(window.localStorage.getItem('admin'))
    if (!admin){
      next({path:'/'})
    }else{
      //校验token的合法性
      axios({
        url:'http://localhost:8181/user/checkToken',
        method:'get',
        headers:{
          token:admin.token
        }
      }).then((response)=>{
        console.log(response.data)
        if(!response.data){
          console.log('校验失败')
          next({path:'/error'})
        }
      })
      next()
    }
  }
})
export default router
